﻿using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using ZT.Core.IService;
using ZT.Core.MiddleWare;
using ZT.Core.Utility;

namespace ZT.Core.API.Controllers
{
    /// <summary>
    /// 文件
    /// </summary>
    [Route("api/attachFile")]
    [ApiController]
    public class AttachFileController : BaseController
    {
       
        private IAttachFile bll = null;
        public AttachFileController(IAttachFile attachFile)
        {
            bll = attachFile;
            Services.Add(attachFile);
        }
        /// <summary>
        /// 文件上传，返回服务器文件地址
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("uploadFile")]
        public async Task<ResultModel<string>> UploadImg()
        {
            try
            {
                var files = Request.Form.Files;
                if (files == null || files.Count == 0)
                {
                    throw new Exception("没有需要上传的文件");
                }
                if (!Directory.Exists(Environment.CurrentDirectory + "/wwwroot/files"))
                {
                    var s = Environment.CurrentDirectory + "/wwwroot/files";
                    Directory.CreateDirectory(s);
                }
                //文件名称
                var dbPath = "";
                foreach (var item in files)
                {
                    string ImgName = Guid.NewGuid() + Path.GetExtension(item.FileName);
                    string path = Environment.CurrentDirectory + "/wwwroot/files/" + ImgName;
                    using (FileStream fs = System.IO.File.Create(path))
                    {
                       await item.CopyToAsync(fs);
                        fs.Flush();
                    }
                    dbPath = "/files/" + ImgName;
                }
                return new ResultModel<string>(dbPath);
            }
            catch (Exception ex)
            {
                return new ResultModel<string>(ex);
            }
        }
        /// <summary>
        /// 用与没有提交表单删除文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        [HttpGet,Route("delFileByPath/{filePath}")]
        public ResultModel<bool> DelFileByPath(string filePath)
        {
            try
            {
             //  var filepath = _host+ filePath;
                //if (System.IO.File.Exists(filepath))
                //{
                //    System.IO.File.Delete(filepath);
                //}
                return new ResultModel<bool>(true);
            }
            catch (Exception ex)
            {
                return new ResultModel<bool>(ex);
            }
        }
    }
}